import React from 'react'
import menuRoute from 'routes/menuRoute'
import { connect } from 'react-redux'
import {dealCache, deepFullCopy, messages, queryCurrencyPrecision} from 'share/common'
import { Form, Tabs, message, Popover } from 'antd'
const TabPane = Tabs.TabPane;
import moment from 'moment'
import SearchArea from 'components/search-area'
import SlideFrame from 'components/slide-frame'
import RepaymentDetailFrame from 'containers/loan-billing/template/refund-content'
import loanAndRefundService from 'containers/financial-management/loan-and-refund/loan-and-refund.service'
import 'styles/financial-management/loan-and-refund/loan-and-refund.scss'
import configureStore from "stores";
import {setLoanAndRefund} from "actions/cache";
import {setLoanParams} from 'actions/billing'
import ResizeTable from 'components/resize-table'
import viewLine from "containers/loan-billing/template/view-line";
import ViewHistory from "containers/loan-billing/template/view-history";
let cacheSearchData={};

class LoanAndRefund extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      tab: 'all',
      refundFrame: false,
      globalSearchForm: [
        {type: 'input', id: 'payeeKey', label: messages('financial-management.key575')/*收款人*/, placeholder: messages('financial-management.key617')/*请输入姓名/工号/供应商编号/供应商名称*/},
        {type: 'input', id: 'companyName', label: messages('financial-management.key576')/*借款公司*/, placeholder: messages('financial-management.key618')/*请输入公司名称*/},
      ],
      refundSearchForm: [
        {type: 'items', id: 'dataRange', items: [
          {type: 'date', id: 'startDateTime', label: messages('financial-management.key243'/*还款提交日期从*/)},
          {type: 'date', id: 'endDateTime', label: messages('financial-management.key244'/*还款提交日期至*/)}
        ]},
        {type: 'input', id: 'payeeKey', label: messages('financial-management.key575')/*收款人*/},
        {type: 'input', id: 'employeeKey', label: messages('financial-management.key577')/*借款人*/},
        {type: 'input', id: 'businessCodeR', label: messages('financial-management.key245'/*还款单号*/)},
        {type: 'input', id: 'businessCodeL', label: messages('financial-management.key246'/*借款单号*/)},
        {
          type: 'searcher',
          id: 'formOIDs',
          label: messages('financial-management.key176'/*表单类型*/),
          listType: 'authority_form',
          descriptionKey: 'companyName',
          labelKey: 'formName',
          valueKey: 'formOID',
          listExtraParams: {formType: 3001}
        },
        {type: 'radio', id: 'status', label: messages('financial-management.key239'/*还款状态*/),
          options: [
            {label: messages('financial-management.key240'/*全部*/),value: '100'},
            {label: messages('financial-management.key172')/*待确认*/,value: '1001'},
            {label: messages('financial-management.key578')/*已完成*/,value: '1002'},
          ],
          defaultValue: '1001'
        }
      ],
      loanSearchForm: [
        {type: 'items', id: 'dataRange', items: [
          {type: 'date', id: 'startDateTime', label: messages('financial-management.key247'/*借款提交日期从*/)},
          {type: 'date', id: 'endDateTime', label: messages('financial-management.key248'/*借款提交日期至*/)}
        ]},
        {type: 'input', id: 'payeeKey', label: messages('financial-management.key575')/*收款人*/},
        {type: 'input', id: 'employeeKey', label: messages('financial-management.key579')/*申请人/代理人*/},
        {type: 'input', id: 'businessCodeL', label: messages('financial-management.key246'/*借款单号*/)},
        {
          type: 'searcher',
          id: 'formOIDs',
          label: messages('financial-management.key176'/*表单类型*/),
          listType: 'authority_form',
          descriptionKey: 'companyName',
          labelKey: 'formName',
          valueKey: 'formOID',
          listExtraParams: {formType: 3001}
        },
        {type: 'radio', id: 'status', label: messages('financial-management.key239'/*还款状态*/),
          options: [
            {label: messages('financial-management.key240'/*全部*/),value: '1000'},
            {label: messages('financial-management.key241')/*有欠款*/,value: '1005'},
            {label: messages('financial-management.key578')/*已完成*/,value: '1007'},
          ],
          defaultValue: '1005'
        }
      ],
      searchParams: {},
      globalColumns: [
        {title: messages('common.sequence'/*序号*/), dataIndex: 'index', width: 48, render: (value, record, index) => index + 1 + this.state.pageSize * this.state.page},
        {title: messages('financial-management.key580')/*工号/供应商编号*/, dataIndex: 'payeeCode'},
        {title: messages('financial-management.key575')/*收款人*/, dataIndex: 'payeeName'},
        {title: messages('financial-management.key576')/*借款公司*/, dataIndex: 'companyName'},
        {title: messages('financial-management.key135'/*币种*/), dataIndex: 'currencyCode', width: 48},
        {title: messages('financial-management.key250'/*借款总额*/), dataIndex: 'loanSum',align:"right", render:(value,record) => this.filterMoney(value,queryCurrencyPrecision(record.currencyCode))},
        {title: messages('financial-management.key251'/*待还款总额*/), dataIndex: 'stayWriteOffSum',align:"right", render:(value,record) => this.filterMoney(value,queryCurrencyPrecision(record.currencyCode))},
      ],
      refundColumns: [
        {title: messages('common.sequence'/*序号*/), dataIndex: 'index', width: 48, render: (value, record, index) => index + 1 + this.state.pageSize * this.state.page},
        {title: messages('financial-management.key580')/*工号/供应商编号*/, dataIndex: 'payeeCode'},
        {title: messages('financial-management.key575')/*收款人*/, dataIndex: 'payeeName'},
        {title: messages('financial-management.key252'/*还款提交日期*/), dataIndex: 'createDate',width:120, render: value => moment(value).format('YYYY-MM-DD')},
        {title: messages('financial-management.key581')/*还款人*/, dataIndex: 'fullName'},
        {title: messages('financial-management.key245'/*还款单号*/), dataIndex: 'businessCode'},
        {title: messages('financial-management.key246'/*借款单号*/), dataIndex: 'loanBusinessCode'},
        {title: messages('financial-management.key135'/*币种*/), dataIndex: 'currencyCode', width: 48},
        {title: messages('financial-management.key253'/*还款金额*/), dataIndex: 'repaymentAmount',align:"right", render:(value,record) => this.filterMoney(value,queryCurrencyPrecision(record.currencyCode))},
        {title: "凭证编号", dataIndex: 'origDocumentSequence',align:"left", render:(value,record) => value || '-'},
        {title: "借款单类型", dataIndex: 'loanTypeName',align:"left", render:(value,record) => value || '-'},
        {title: messages('financial-management.key254'/*操作*/), dataIndex: 'oid', render: (value, record) => this.confirmColumns(value, record)}
      ],
      loanColumns: [
        {title: messages('common.sequence'/*序号*/), dataIndex: 'index', width: 48, render: (value, record, index) => index + 1 + this.state.pageSize * this.state.page},
        { title: messages('financial-management.key134')/*单号*/, dataIndex: 'businessCode',
          render: (value, record) => <a onClick={e => this.handleLoanRowClick(e, record)}>{value}</a> },
        {title: messages('financial-management.key576')/*借款公司*/, dataIndex: 'companyName'},
        {title: messages('financial-management.key579')/*申请人/代理人*/, dataIndex: 'applicantName', render: (value,record) => record.submittedBy === record.applicantOid ? value : `${value}/${record.submittedName}`},
        { title: messages('financial-management.key669')/*借款类型*/, dataIndex: 'loanTypeName' },
        { title: messages('financial-management.key894')/*事由*/, dataIndex: 'remark' },
        {title: messages('financial-management.key582')/*借款行号*/, dataIndex: 'sequence'},
        {title: messages('financial-management.key256'/*借款提交日期*/), dataIndex: 'submittedDate',width:120, render: value => moment(value).format('YYYY-MM-DD')},
        // {title: messages('common.matter')/*事由*/, dataIndex: 'remark', render: value => {return <Popover placement="topLeft" content={value}>{value}</Popover>}},
        {title: messages('financial-management.key575')/*收款人*/, dataIndex: 'payeeName'},
        {title: messages('financial-management.key135'/*币种*/), dataIndex: 'currencyCode', width: 48},
        {title: messages('financial-management.key257'/*借款金额*/), dataIndex: 'amount', align:"right",render:(value,record) => this.filterMoney(value,queryCurrencyPrecision(record.currencyCode))},
        {title: messages('financial-management.key258'/*待还款金额*/), dataIndex: 'stayWriteOffAmount', align:"right",render:(value,record) => this.filterMoney(value,queryCurrencyPrecision(record.currencyCode))},
        {title: "凭证编号", dataIndex: 'origDocumentSequence',align:"left", render:(value,record) => value || '-'},
        {title: messages('financial-management.key254')/*操作*/, dataIndex: 'operator', render: (value, record) => <div>
            <a onClick={e => this.handleViewHistory(e,record)}>{messages('loan-billing.key121')/*还款历史*/}</a>
          </div>
        }
      ],
      data: [],
      page: 0,
      pageSize: 10,
      pagination: {
        total: 0,
        showQuickJumper: true,
        showSizeChanger: true,
        onShowSizeChange: this.onChangePagerSize,
        pageSizeOptions: ['10','20','50','100','200']
      },
      refundParams: {}, //还款单管理侧滑参数
      overallSubList: menuRoute.getRouteItem('overall-sub-list','key'), //全局查看列表页
      requestDetail: menuRoute.getRouteItem('loan-detail-refund','key'), //申请单详情页
      expenseDetailView: menuRoute.getRouteItem('loan-refund-detail-expense', 'key'), //费用申请单详情
      overallRestaurantList: menuRoute.getRouteItem('overall-restaurant-list', 'key'), // 餐厅全局查看列表页
      viewFrame: false,
      viewId: '',
      historyModal: false,
      historyId: '',
      loanAndRepaySearchForm: [
        {type: 'input', id: 'costCenterItemName', label: messages('financial-management.key825')/*餐厅名称*/, placeholder: messages('financial-management.key1243')/*请输入餐厅编码*/},
        {type: 'input', id: 'companyName', label: messages('financial-management.key576')/*借款公司*/, placeholder: messages('financial-management.key618')/*请输入公司名称*/},
      ],
      restaurantColumns: [
        {title: messages('common.sequence'/*序号*/), dataIndex: 'index', width: 48, render: (value, record, index) => index + 1 + this.state.pageSize * this.state.page},
        {title: messages('setting.key290')/*成本中心名称*/, dataIndex: 'costCenterItemName'},
        {title: messages('financial-management.key576')/*借款公司*/, dataIndex: 'companyName'},
        {title: messages('financial-management.key135'/*币种*/), dataIndex: 'currencyCode', width: 48},
        {title: messages('financial-management.key250'/*借款总额*/), dataIndex: 'loanSum',align:"right", render:(value,record) => this.filterMoney(value,queryCurrencyPrecision(record.currencyCode))},
        {title: messages('financial-management.key251'/*待还款总额*/), dataIndex: 'stayWriteOffSum',align:"right", render:(value,record) => this.filterMoney(value,queryCurrencyPrecision(record.currencyCode))},
      ],
    }
  }

  componentDidMount() {
    this.setState({ tab: 'all' },() => {
      this.getCache()
    })
  }
  //存储筛选数据缓存
  setCache(result){
    let {tab ,page} = this.state;
    let temp = deepFullCopy(result);
    temp.tab = tab;
    temp.page = page;
    //后台接收的status是一个数组 所以必须转换
    //1000 => [1005,1006,1007] 100 => [1001,1002] 1005 => [1005,1006]
    //下次后台改这里一定要逼后台优化
    if(temp.status){
      temp.status.length && temp.status.length > 2 && (temp.status = '1000');
      temp.status.length && temp.status.length === 2 && temp.status.indexOf('1005') > -1 && (temp.status = '1005');
      temp.status.length && temp.status.length === 2 && temp.status.indexOf('1001') > -1 && (temp.status = '100');
    }
    cacheSearchData = temp;
  }
  //获取筛选数据缓存
  getCache(){
    let result = this.props.loanAndRefund;
    if(result&&JSON.stringify(result) !== "{}"){
      cacheSearchData=result;
      this.dealCache(result);
    }
    else{
      this.getList()
    }

  };
  //处理筛选缓存数据
  dealCache(result) {
    let { globalSearchForm, refundSearchForm, loanSearchForm ,tab, page, loanAndRepaySearchForm} = this.state;
    if (result) {
      console.log('result', result)
      tab = result.tab;
      page = result.page;
      let searchForm = tab === 'all' ? globalSearchForm : tab === 'refund' ? refundSearchForm : tab === 'loan' ? loanSearchForm : loanAndRepaySearchForm;
      let searchFormKey = tab === 'all' ? 'globalSearchForm' : tab === 'refund' ? 'refundSearchForm' : tab === 'loan' ? 'loanSearchForm' : 'loanAndRepaySearchForm';
      let defaultSearchForm = deepFullCopy(searchForm);
      dealCache(defaultSearchForm, result);
      this.setState({ tab, [searchFormKey]: defaultSearchForm, page}, () => {
        this.onSearch(result);
        configureStore.store.dispatch(setLoanAndRefund(null));
      })
    }
  }

  handleViewHistory = (e,record) => {
    e.stopPropagation();
    this.setState({ historyId: record.id }, () => this.setState({ historyModal: true }));
  };

  onChangeTabs = (tab) => {
    let temp = {};
    tab === 'refund' && (temp.status = '1001');
    tab === 'loan' && (temp.status = ['1005','1006']);
    const { pagination } = this.state;
    pagination.total = 0;
    this.setState({
      tab,
      searchParams: temp,
      page: 0,
      pagination
    }, () => {
      this.formRef && this.formRef.setValues({
        employeeKey: '',
        startDateTime: '',
        endDateTime: '',
        payeeKey: '',
        status: typeof temp.status === 'object' ? temp.status[0] : temp.status
      });
      this.setCache(temp);
      this.getList()
    })
  };

  getList = () => {
    const { tab, page, pageSize, searchParams, pagination } = this.state;
    let values = JSON.parse(JSON.stringify(searchParams));
    values.status && (values.status = (values.status === '1000' ?  ['1005','1006','1007'] : (values.status === '100' ? ['1001','1002'] : (values.status === '1005' ? ['1005','1006'] : values.status))));
    let method = tab === 'all' ? 'getGlobalList' : tab === 'refund' ? 'getRefundList' : tab === 'loan' ? 'getLoanList' : 'getRestaurantList';
    this.setState({ loading: true });
    loanAndRefundService[method](page, pageSize, values).then(res => {
      pagination.total = Number(res.headers['x-total-count']) || 0;
      pagination.current = page + 1;
      pagination.onChange = this.onChangePaper;
      this.setState({
        loading: false,
        data: res.data,
        pagination
      })
    }).catch(() => {
      this.setState({
        loading: false
      });
      message.error(messages('common.error1'))
    })
  };

  onChangePagerSize = (current, size) => {
    if(size !== this.state.pageSize)
      this.setState({
        page: 0,
        pageSize: size
      },() => {
        this.getList()
      })
  };

  onChangePaper = (page) => {
    if (page - 1 !== this.state.page) {
      this.setState({ page: page - 1 }, () => {
        this.getList()
      })
    }
  };

  onSearch = (values) => {
    values.status && (values.status = (values.status === '1000' ?  ['1005','1006','1007'] : (values.status === '100' ? ['1001','1002'] : (values.status === '1005' ? ['1005','1006'] : values.status))));
    this.setCache(JSON.parse(JSON.stringify(values)));
    values.startDateTime && (values.startDateTime = moment(values.startDateTime).format('YYYY-MM-DD 00:00:00'));
    values.endDateTime && (values.endDateTime = moment(values.endDateTime).format('YYYY-MM-DD 23:59:59'));
    this.setState({
      searchParams: values,
      page: 0
    },() => {
      this.getList()
    })
  };

  onClear = () => {
    const { tab } = this.state;
    let temp = {};
    tab === 'refund' && (temp.status = '1001');
    tab === 'loan' && (temp.status = '1005');
    this.setState({
      searchParams: temp,
      page: 0
    }, () => {
      this.formRef && this.formRef.setValues({
        employeeKey: '',
        startDateTime: '',
        endDateTime: '',
        payeeKey: '',
        status: temp.status,
        businessCodeL: '',
        businessCodeR: '',
        businessCode: '',
        companyName: '',
        costCenterItemName: ''
      });
      this.setCache(temp);
      this.getList()
    });
  };

  //还款单管理侧滑
  showRefundDetailSlide = (flag) => {
    this.setState({ refundFrame: flag })
  };

  //关闭确认收款侧滑
  handleRefundAfterClose = (value) => {
    this.setState({ refundFrame: false }, () => {
      value && this.getList()
    })
  };

  //确认收款
  confirmRefund = (oid, record) => {
    if (record.expenseReportOid) {
      this.context.router.push(this.state.expenseDetailView.url.replace(':expenseReportOID', record.expenseReportOid))
    } else {
      this.setState({ refundParams: record.repaymentOid },() => {
        this.showRefundDetailSlide(true)
      })
    }
  };

  //进入全局查看详情
  handleOverallRowClick = (record) => {
    configureStore.store.dispatch(setLoanAndRefund(cacheSearchData));
    let tempState = {payeeId: record.payeeId,currencyCode: record.currencyCode,companyID:record.companyID};
    configureStore.store.dispatch(setLoanParams(tempState));
    this.context.router.push(this.state.overallSubList.url);
  };

  //借款单管理详情
  handleLoanRowClick = (e, record) => {
    e.stopPropagation();
    configureStore.store.dispatch(setLoanAndRefund(cacheSearchData));
    this.context.router.push(this.state.requestDetail.url.replace(':formOID', record.formOid).replace(':loanBillOID', record.loanBillOid).replace(':backType','history') + '?tab=loan')
  };

  confirmColumns = (value,record) => {
    if(!this.checkNewAuth()){
      return <a onClick={() => this.confirmRefund(value, record)}>{messages('common.detail'/*详情*/)}</a>
    }
    return <a onClick={() => this.confirmRefund(value, record)}>{record.expenseReportOid || !this.checkPageRole('REPAYMENTSLIPMANAGEMENT', 2) ? messages('common.detail'/*详情*/) : (record.status === 1001 ? messages('financial-management.key255'/*确认收款*/) : messages('common.detail'/*详情*/))}</a>;
  };

  handleView = record => {
    if (record.stayWriteOffAmount === 0) {
      this.setState({ viewFrame: true, viewId: record.id });
    }
  };

  handleViewRefund = item => {
    if (item.type === 2 || item.type === 3) {
      this.context.router.push(menuRoute.getRouteItem('expense-report-detail').url.replace(':expenseReportOID', record.expenseReportOid).replace(':pageFrom','my'));
    } else {
      this.setState({ refundFrame: true, refundParams: item.repaymentOid, historyModal: false });
    }
  };

  //进入餐厅全局查看详情
  handleOverallRestaurantRowClick = (record) => {
    configureStore.store.dispatch(setLoanAndRefund(cacheSearchData));
    console.log('record', record)
    let tempState = {costCenterItemOID: record.costCenterItemOID,currencyCode: record.currencyCode,companyID:record.companyID};
    configureStore.store.dispatch(setLoanParams(tempState));
    this.context.router.push(this.state.overallRestaurantList.url);
  };

  render() {
    const { loading, tab, refundFrame, globalSearchForm, refundSearchForm, loanSearchForm, globalColumns,
      refundColumns, loanColumns, data, pagination, refundParams, viewFrame, viewId, historyModal, historyId, loanAndRepaySearchForm, restaurantColumns } = this.state;
    return (
      <div className="loan-and-refund">
        <Tabs type="card" activeKey={tab} onChange={this.onChangeTabs}>
          {this.checkPageRole('LOANGLOBALVIEW') && <TabPane tab={messages('financial-management.key259'/*借还款全局查看*/)} key="all"/>}
          {this.checkPageRole('REPAYMENTSLIPMANAGEMENT') && <TabPane tab={messages('financial-management.key918')/*还款管理*/} key="refund"/>}
          {this.checkPageRole('LOANBILLMANAGEMENT') &&<TabPane tab={messages('financial-management.key919')/*借款管理*/} key="loan"/>}
          {this.checkPageRole('RESTAURANTLOANANDREPAYVIEW') &&<TabPane tab={messages('setting.key2831')/*餐厅借还款全局查看*/} key="loanAndRepay"/>}
        </Tabs>

        <SearchArea searchForm={tab === 'all' ? globalSearchForm : tab === 'refund' ? refundSearchForm : tab === 'loan' ? loanSearchForm : loanAndRepaySearchForm}
                    wrappedComponentRef={inst => this.formRef = inst}
                    submitHandle={this.onSearch}
                    isReturnLabel={true}
                    clearHandle={this.onClear}/>
        <div className="table-header">
          <div className="table-header-title">{messages('common.total', {total: pagination.total || 0})/*共 total 条数据*/}</div>
        </div>
        <ResizeTable
          rowKey={(record, index) => index}
          columns={tab === 'all' ? globalColumns : tab === 'refund' ? refundColumns : tab === 'loan' ? loanColumns : restaurantColumns}
          dataSource={data}
          pagination={pagination}
          loading={loading}
          onRow={tab === 'all' ? (record => ({onClick: () => this.handleOverallRowClick(record)})) :
            tab === 'loan' ? (record => ({onClick: () => this.handleView(record)})) :
            tab === 'loanAndRepay' ? (record => ({onClick: () => this.handleOverallRestaurantRowClick(record)})) : ''
          }
          bordered
          size="middle"
        />
        <SlideFrame show={refundFrame}
                    title={messages('financial-management.key262'/*还款单详情*/)}
                    content={RepaymentDetailFrame}
                    params={{
                      refundFrame,
                      refundParams,
                      location:this.props.location
                    }}
                    onClose={() => this.showRefundDetailSlide(false)}
                    afterClose={this.handleRefundAfterClose}/>
        <SlideFrame
          show={viewFrame}
          title={messages('loan-billing.key118')/*查看借款计划*/}
          key='viewLine'
          content={viewLine}
          params={{
            viewFrame,
            viewId
          }}
          onClose={() => {this.setState({viewFrame: false})}}
          afterClose={() => {this.setState({viewFrame: false})}}
        />
        <ViewHistory
          visible={historyModal}
          id={historyId}
          handleViewRefund={this.handleViewRefund}
          close={() => this.setState({historyModal: false})}
        />
      </div>
    )
  }
}

LoanAndRefund.contextTypes = {
  router: React.PropTypes.object
};
function mapStateToProps(state) {
  return {
    loanAndRefund: state.cache.loanAndRefund,
  }
}
const WrappedLoanAndRefund = Form.create()(LoanAndRefund);

export default connect(mapStateToProps)(WrappedLoanAndRefund);
